package com.lange.fileManagement.controller;

import com.lange.fileManagement.service.CaptchaService;
import com.lange.fileManagement.utils.CaptchaGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaService captchaService;

    private final CaptchaGenerator captchaGenerator = new CaptchaGenerator();

    /*获取验证码*/
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String captchaCode = captchaGenerator.generateCaptchaCode();
        BufferedImage captchaImage = captchaGenerator.generateCaptcha(captchaCode);

        // 将验证码存储到session中以便验证
        captchaService.addCaptcha(captchaCode);

        response.setContentType("image/png");
        ImageIO.write(captchaImage, "png", response.getOutputStream());
    }
}
